import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 定义 state
const state = {
  user: null,       // 用户信息
  allRatings: []    // 所有评分
}

// 定义 mutations
const mutations = {
  // 设置用户信息
  SET_USER(state, user) {
    state.user = user
  },
  // 设置所有评分
  SET_ALL_RATINGS(state, ratings) {
    state.allRatings = ratings
  },
  // 更新或添加评分
  UPDATE_OR_ADD_RATING(state, rating) {
    const index = state.allRatings.findIndex(
      (item) => item.userId === rating.userId && item.movieId === rating.movieId
    )
    if (index >= 0) {
      // 如果存在，更新评分
      state.allRatings[index].rating = rating.rating
    } else {
      // 如果不存在，添加新评分
      state.allRatings.push(rating)
    }
  },
  // 更新用户信息
  UPDATE_USER(state, updatedUser) {
    state.user = { ...state.user, ...updatedUser }
  }
}

// 定义 actions
const actions = {
  // 设置用户信息
  setUser({ commit }, user) {
    commit('SET_USER', user)
  },
  // 设置所有评分
  setAllRatings({ commit }, ratings) {
    commit('SET_ALL_RATINGS', ratings)
  },

  // 更新或添加评分
  updateOrAddRating({ commit }, rating) {
    commit('UPDATE_OR_ADD_RATING', rating)
  }
}

// 定义 getters
const getters = {
  // 获取用户信息
  getUser: (state) => state.user,
  // 获取所有评分
  getAllRatings: (state) => state.allRatings,
  // 查询评分
  getRating: (state) => ({ userId, movieId }) => {
    const index = state.allRatings.findIndex(item => {
      return item.userId == userId && item.movieId == movieId
    })
    if (index >= 0) {
      return state.allRatings[index].rating
    }
    else {
      return 1
    }
  },
}

// 创建并暴露 store
export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})